let requestLog = require('../model').requestLog;
exports.logRouter = function (req, res, next) {
    res.logArray = [];
    let path = req.path,
        startAt = req.requestAt || new Date().getTime(),
        reqHeaders = JSON.parse(JSON.stringify(req.headers)),
        oldWrite = res.write,
        oldEnd = res.end,
        body = '',
        chunks = [];
    req.originBody = JSON.parse(JSON.stringify(req.body));
    res.write = function (chunk) {
        chunks.push(chunk);
        oldWrite.apply(res, arguments);
    };

    res.end = function (chunk) {
        if (chunk)
            chunks.push(chunk);

        body = Buffer.concat(chunks).toString('utf8');

        oldEnd.apply(res, arguments);
    };
    res.on('finish', logger);
    res.on('close', logger);
    function logger() {
        try {
            body = JSON.parse(body)
        }
        catch (e) {
        }
        let logData = {
            method: req.method,
            url: path,
            requestTime: new Date().getTime() - startAt,
            requestBody: req.originBody,
            requestHeaders: reqHeaders,
            responseBody: body,
            requestAt: startAt
        };
        requestLog.create(logData);
    }
    next();
};

